package com.ailesson.order.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.ailesson.common.except.ServiceException;
import com.ailesson.order.service.WxPayMpService;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayMpServiceImpl implements WxPayMpService {

    @Autowired
    protected WxPayService wxPayService;

    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            WxPayOrderQueryResult orderQueryResult = wxPayService.queryOrder(null, orderNo);
            Map<String, String> map = new HashMap<>();
            map.put("state",orderQueryResult.getTradeState());
            map.put("tradeStateDesc",orderQueryResult.getTradeStateDesc());
            return map;
        } catch (WxPayException e) {
            throw new ServiceException(Integer.parseInt(e.getErrCode()),e.getMessage());
        }
    }

    @Override
    public Map<String, Object> createJsapi(String orderNo) {
        try {
            WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
            request.setBody("订单支付");
            request.setOpenid("111");
            request.setOutTradeNo(orderNo);
            request.setTotalFee(1);
            request.setSpbillCreateIp("127.0.0.1");
            request.setSignType("MD5");
            request.setTimeStart(LocalDateTimeUtil.format(LocalDateTime.now(),"yyyyMMddHHmmss"));
            WxPayUnifiedOrderResult wxPayUnifiedOrderResult = wxPayService.unifiedOrder(request);

            //返回结果
            Map<String, Object> result = new HashMap();
            String packages = "prepay_id=" + wxPayUnifiedOrderResult.getPrepayId();
            result.put("appId", wxPayUnifiedOrderResult.getAppid());
            result.put("timeStamp", request.getTimeStart());
            result.put("nonceStr", wxPayUnifiedOrderResult.getNonceStr());
            result.put("signType", "MD5");
            result.put("paySign", wxPayUnifiedOrderResult.getSign());
            result.put("package", packages);
            log.info("支付返回结果:{}",result);
            return result;
        } catch (WxPayException e) {
            throw new ServiceException(Integer.parseInt(e.getErrCode()),e.getMessage());
        }
    }
}
